package com.hyp.pay.device;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.hyp.pay.http.HyqApis;
import com.hyp.pay.utils.SPUtil;
import com.newland.me.ConnUtils;
import com.newland.me.DeviceManager;
import com.newland.mtype.ConnectionCloseEvent;
import com.newland.mtype.Device;
import com.newland.mtype.ExModuleType;
import com.newland.mtype.ModuleType;
import com.newland.mtype.event.DeviceEventListener;
import com.newland.mtype.module.common.cardreader.K21CardReader;
import com.newland.mtype.module.common.emv.EmvModule;
import com.newland.mtype.module.common.iccard.ICCardModule;
import com.newland.mtype.module.common.light.IndicatorLight;
import com.newland.mtype.module.common.pin.K21Pininput;
import com.newland.mtype.module.common.printer.PrintContext;
import com.newland.mtype.module.common.printer.Printer;
import com.newland.mtype.module.common.printer.PrinterResult;
import com.newland.mtype.module.common.printer.PrinterStatus;
import com.newland.mtype.module.common.rfcard.K21RFCardModule;
import com.newland.mtype.module.common.scanner.BarcodeScanner;
import com.newland.mtype.module.common.scanner.BarcodeScannerManager;
import com.newland.mtype.module.common.security.SecurityModule;
import com.newland.mtype.module.common.serialport.SerialModule;
import com.newland.mtype.module.common.sm.SmModule;
import com.newland.mtype.module.common.storage.Storage;
import com.newland.mtype.module.common.swiper.K21Swiper;
import com.newland.mtypex.nseries3.NS3ConnParams;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

//import com.newland.mtype.ExModuleType;
//import com.newland.mtype.module.common.serialport.SerialModule;6

public class N900Device2 extends AbstractDevice {
	private static final String K21_DRIVER_NAME = "com.newland.me.K21Driver";
	private static Context baseActivity;
	private static N900Device2 n900Device2=null;
	private static DeviceManager deviceManager ;
	private Printer printer;
	private static String paymentId1;
	private static String paymentTime1;
	private static String moneyFloat1;
	private static String text1;
	private static String pay1;
	private static String SignPayerName1;
	private static String name1;
	static Bitmap bitmap1;
	static Bitmap mBitmap;

	private N900Device2(Activity baseactivity) {
		N900Device2.baseActivity = baseactivity;
	}

	public static N900Device2 getInstance(Activity baseactivity) {
		if (n900Device2 == null) {
			synchronized (N900Device2.class) {
				if (n900Device2 == null) {
					n900Device2 = new N900Device2(baseactivity);
				}
			}
		}                                                 
		N900Device2.baseActivity = baseactivity;
		return n900Device2;
	}


	@Override
	public void connectDevice() {
		Looper.prepare();
//		Toast.makeText(baseActivity, "设备连接中..", Toast.LENGTH_SHORT).show();
//		baseActivity.showMessage("设备连接中..", Const.MessageTag.TIP);
		try {
			deviceManager = ConnUtils.getDeviceManager();
			deviceManager.init(baseActivity, K21_DRIVER_NAME, new NS3ConnParams(), new DeviceEventListener<ConnectionCloseEvent>() {
				@Override
				public void onEvent(ConnectionCloseEvent event, Handler handler) {
					if (event.isSuccess()) {
						Toast.makeText(baseActivity, "设备被客户主动断开！", Toast.LENGTH_SHORT).show();
//						baseActivity.showMessage("设备被客户主动断开！", Const.MessageTag.NORMAL);
					}
					if (event.isFailed()) {
						Toast.makeText(baseActivity, "设备链接异常断开！", Toast.LENGTH_SHORT).show();
//						baseActivity.showMessage("设备链接异常断开！", Const.MessageTag.ERROR);
					}
				}

				@Override
				public Handler getUIHandler() {
					return null;
				}
			});
//			Toast.makeText(baseActivity, "N900设备控制器已初始化!", Toast.LENGTH_SHORT).show();
//			baseActivity.showMessage("N900设备控制器已初始化!", Const.MessageTag.TIP);
			deviceManager.connect();
			deviceManager.getDevice().setBundle(new NS3ConnParams());
			Log.i("olj","设备连接成功.");
			Toast.makeText(baseActivity, "设备连接成功.", Toast.LENGTH_SHORT).show();
//			baseActivity.showMessage("设备连接成功.", Const.MessageTag.TIP);


			printer = n900Device2.getPrinter();

			print();

		} catch (Exception e1) {
			e1.printStackTrace();
			Toast.makeText(baseActivity, "链接异常,请检查设备或重新连接...", Toast.LENGTH_SHORT).show();
//			baseActivity.showMessage("链接异常,请检查设备或重新连接..."+e1, Const.MessageTag.ERROR);
		}
		Looper.loop();
	}


	private void print() {
		new Thread(new Runnable() {
			//Message msg = new Message();

			@Override
			public void run() {
//				Bitmap	bitmap2 =netPicToBmp(HyqApis.HOST+SPUtil.getSignPayerName());
//				Bitmap bitmap3=netPicToBmp(HyqApis.HOST+SPUtil.getDraweeName());
//				Log.i("olj",HyqApis.HOST+SPUtil.getSignPayerName());
//				Log.i("olj",HyqApis.HOST+SPUtil.getDraweeName());
				if (printer.getStatus() != PrinterStatus.NORMAL) {
					// 缺纸
					if (printer.getStatus() == PrinterStatus.OUTOF_PAPER) {
						Toast.makeText(baseActivity, "缺纸", Toast.LENGTH_SHORT).show();
						//handler.sendEmptyMessage(3);
						return;
					}
					Log.d("TAG", "打印失败！打印机状态不正常" + "\r\n");

				} else {
					try {
						StringBuffer scriptBuffer = new StringBuffer();
						scriptBuffer.append("!hz l\n !asc l\n");// 设置标题字体为大号
						scriptBuffer.append("!yspace 15\n !gray 10\n");// 设置行间距
						scriptBuffer.append("*text c 万众收款宝 \n");
						scriptBuffer.append("!hz s\n !asc s\n");// 设置内容字体为中号
						scriptBuffer.append("!yspace 5\n !gray 8\n ");// 设置内容行间距
						scriptBuffer.append("*line" + "\n");// 打印虚线
						if (0 == 0) {
							scriptBuffer.append("*text l 商户存根                          请妥善保管\n ");
						} else {
							scriptBuffer.append("*text l 持卡人存根                        请妥善保管\n ");
						}
						scriptBuffer.append("*line" + "\n");// 打印虚线
						scriptBuffer.append("*text l 交易金额:\n");
						scriptBuffer.append("!hz l\n !asc l\n");// 设置标题字体为大号
						scriptBuffer.append("!yspace 15\n !gray 10\n");// 设置行间距
						scriptBuffer.append("*text l "+ SPUtil.getCharge()+"    RMB " + "" + "\n");
						scriptBuffer.append("!hz n\n !asc n\n");// 设置内容字体为中号
						scriptBuffer.append("!yspace 10\n !gray 5\n ");// 设置内容行间距
						scriptBuffer.append("*text l 收款人:" + SPUtil.getUsername() + "\n");
						scriptBuffer.append("*text l 商品摘要:" + "万众汇聚付款类" + "\n");
						scriptBuffer.append("*text l 当前状态:" + SPUtil.getText() + "\n");
						scriptBuffer.append("*text l 操作员号："+ Build.DISPLAY+"\n");
						scriptBuffer.append("*text l 支付时间:" + SPUtil.getPaymentTime()+ "\n");
						scriptBuffer.append("*text l 支付方式:" + SPUtil.getPaymode()+ "\n");
						scriptBuffer.append("!hz n\n !asc n\n");// 设置内容字体为中号
						scriptBuffer.append("!yspace 10\n !gray 5\n ");// 设置内容行间距
						scriptBuffer.append("*text l 交易单号:" + SPUtil.getPaymentId() + "\n");
						scriptBuffer.append("*text l 平台单号：" + SPUtil.getLogno()+ "\n");
						scriptBuffer.append("*text l 商户单号：" + SPUtil.getShopTradeNo()+ "\n");
						scriptBuffer.append("!hz s\n !asc s\n");//
						scriptBuffer.append("!yspace 10\n !gray 5\n");//
						scriptBuffer.append("*line" + "\n");// 打印虚线
						PrinterResult printScript3 = printer.printByScript(PrintContext.defaultContext(), scriptBuffer.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);

						if (0 == 0) {
							if (mBitmap != null) {
								Log.d("TAG", "bmpDefaultPic ==null");
								scriptBuffer.append("*text l 持卡人签名:\n");
								scriptBuffer.append("*text l  \n");//
								scriptBuffer.append("*text l  \n");//
								scriptBuffer.append("*text l  \n");//
								scriptBuffer.append("*text l 本人确认以上交易，同意将其记入本卡账户\n");
								scriptBuffer.append("*text l 服务热线：021—31695161\n");
								scriptBuffer.append("*text l  \n");//
								scriptBuffer.append("*text l  \n");//
								scriptBuffer.append("*text l  \n");//
								Log.d("TAG", "printScript s--------");
								PrinterResult printResult = printer.printByScript(PrintContext.defaultContext(), scriptBuffer.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);
								Log.d("TAG", "printResult  -------" + printResult);
							} else {

								StringBuffer scriptBuffer1 = new StringBuffer();
								PrinterResult centerRst = printer.printByScript(PrintContext.defaultContext(), ("*qrcode c " +
										HyqApis.HOST+"app_countLogDetail2.html?countLogId="+SPUtil.getID()+"&userId="+SPUtil.getUserid() + "\n").getBytes("GBK"), 60, TimeUnit.SECONDS);
								Log.d("TAG", "printResult  -------" + centerRst);
								scriptBuffer1.append("*text l  \n");//
								scriptBuffer1.append("*text l  \n");//
								scriptBuffer1.append("*text l                 扫一扫查看明细 \n");//
								scriptBuffer1.append("*text l  \n");//
								scriptBuffer1.append("*text l  \n");//
								scriptBuffer1.append("*text l 备注:\n");
								scriptBuffer1.append("*text l 付款人签名:\n");
								scriptBuffer1.append("*line" + "\n");// 打印虚线
								PrinterResult printScript = printer.printByScript(PrintContext.defaultContext(), scriptBuffer1.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);
								Log.d("TAG", "printResult  -------" + printScript);

//								Log.d("olj", mBitmap.toString()+"1111111111111111111111111111");
//											printer.print(0, mBitmap,50, TimeUnit.SECONDS);// 缩小图片尺寸
//
//								printer.print(0, bitmap2,50, TimeUnit.SECONDS);// 缩小图片尺寸

								StringBuffer scriptBuffer2 = new StringBuffer();
								scriptBuffer2.append("!hz s\n !asc s\n");//
								scriptBuffer2.append("!yspace 10\n !gray 5\n");//
								scriptBuffer2.append("*text l 本人确认以上交易，同意将其记入本卡账户\n");
								scriptBuffer2.append("*text l 服务热线：021—31695161\n");
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								scriptBuffer2.append("*text l  \n");//
								PrinterResult printScript2 =printer.printByScript(PrintContext.defaultContext(), scriptBuffer2.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);
								Log.d("TAG", "printResult  -------" + printScript2);

								StringBuffer scriptBuffer3 = new StringBuffer();

								scriptBuffer3.append("*text l 用户存根                        请妥善保管\n ");
								scriptBuffer3.append("*line" + "\n");// 打印虚线
								scriptBuffer3.append("*text l 交易金额:\n");
								scriptBuffer3.append("!hz l\n !asc l\n");// 设置标题字体为大号
								scriptBuffer3.append("!yspace 15\n !gray 10\n");// 设置行间距
								scriptBuffer3.append("*text l "+ SPUtil.getCharge()+"    RMB " + "" + "\n");
								scriptBuffer3.append("!hz n\n !asc n\n");// 设置内容字体为中号
								scriptBuffer3.append("!yspace 10\n !gray 5\n ");// 设置内容行间距
								scriptBuffer3.append("*text l 收款人:" + SPUtil.getUsername() + "\n");
								scriptBuffer3.append("*text l 商品摘要:" + "万众汇聚付款类" + "\n");
								scriptBuffer3.append("*text l 当前状态:" + SPUtil.getText() + "\n");
								scriptBuffer3.append("*text l 操作员号："+ Build.DISPLAY+"\n");
								scriptBuffer3.append("*text l 支付时间:" + SPUtil.getPaymentTime()+ "\n");
								scriptBuffer3.append("*text l 支付方式:" + SPUtil.getPaymode()+ "\n");
								scriptBuffer3.append("!hz n\n !asc n\n");// 设置内容字体为中号
								scriptBuffer3.append("!yspace 10\n !gray 5\n ");// 设置内容行间距
								scriptBuffer3.append("*text l 交易单号:" + SPUtil.getPaymentId() + "\n");
								scriptBuffer3.append("*text l 平台单号：" + SPUtil.getLogno()+ "\n");
								scriptBuffer3.append("*text l 商户单号：" + SPUtil.getShopTradeNo()+ "\n");
								scriptBuffer3.append("!hz s\n !asc s\n");//
								scriptBuffer3.append("!yspace 10\n !gray 5\n");//
								printer.printByScript(PrintContext.defaultContext(), scriptBuffer3.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);

								try {
									StringBuffer scriptBuffer4 = new StringBuffer();
									centerRst = printer.printByScript(PrintContext.defaultContext(), ("*qrcode c " +
											HyqApis.HOST + "app_countLogDetail2.html?countLogId=" + SPUtil.getID() + "&userId=" + SPUtil.getUserid() + "\n").getBytes("GBK"), 60, TimeUnit.SECONDS);
									Log.d("TAG", "printResult  -------" + centerRst);
									scriptBuffer4.append("*text l  \n");//
									scriptBuffer4.append("*text l  \n");//
									scriptBuffer4.append("*text l                 扫一扫查看明细 \n");//
									scriptBuffer4.append("*text l  \n");//
									scriptBuffer4.append("*text l  \n");//
									scriptBuffer4.append("*text l 备注:\n");
									scriptBuffer4.append("*text l 收款人签名:\n");
									scriptBuffer4.append("*line" + "\n");// 打印虚线
									PrinterResult printScriptprintScript = printer.printByScript(PrintContext.defaultContext(), scriptBuffer4.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);

//									Bitmap bitmap = BitmapFactory.decodeResource(baseActivity.getResources(), R.drawable.icon_logo);
//									printer.print(0, bitmap3, 30, TimeUnit.SECONDS);
//									printer.print(0, convertToBitmap(SPUtil.getSignDraweeName(),100,100),50, TimeUnit.SECONDS);// 缩小图片尺寸

									StringBuffer scriptBuffer5 = new StringBuffer();
									scriptBuffer5.append("*text l 本人确认以上交易，同意将其记入本卡账户\n");
									scriptBuffer5.append("*text l 服务热线：021—31695161\n");
									scriptBuffer5.append("*text l  \n");//
									scriptBuffer5.append("*text l  \n");//
									scriptBuffer5.append("*text l  \n");//
									printer.printByScript(PrintContext.defaultContext(), scriptBuffer5.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);
								} catch (UnsupportedEncodingException e) {
									e.printStackTrace();
								}
							}
						} else {
							StringBuffer scriptBuffer7= new StringBuffer();
							scriptBuffer7.append("*text l 本人确认以上交易，同意将其记入本卡账户\n");
							scriptBuffer7.append("*text l 服务热线\n");

							scriptBuffer7.append("*text l 用户存根                        请妥善保管\n ");
							scriptBuffer7.append("*line" + "\n");// 打印虚线
							scriptBuffer7.append("*text l 交易金额:\n");
							scriptBuffer7.append("!hz l\n !asc l\n");// 设置标题字体为大号
							scriptBuffer7.append("!yspace 15\n !gray 10\n");// 设置行间距
							scriptBuffer7.append("*text l "+ SPUtil.getCharge()+"    RMB " + "" + "\n");
							scriptBuffer7.append("!hz n\n !asc n\n");// 设置内容字体为中号
							scriptBuffer7.append("!yspace 10\n !gray 5\n ");// 设置内容行间距
							scriptBuffer7.append("*text l 收款人:" + SPUtil.getUsername() + "\n");
							scriptBuffer7.append("*text l 商品摘要:" + "万众汇聚付款类" + "\n");
							PrinterResult printScript5 =printer.printByScript(PrintContext.defaultContext(), scriptBuffer7.toString().getBytes("gbk"), 60, TimeUnit.SECONDS);


						}



						// 监听纸是否用完
						if (printer.getStatus() == PrinterStatus.OUTOF_PAPER) {
							//handler.sendEmptyMessage(3);
							return;
						}
						//handler.sendEmptyMessage(0);
					} catch (Exception e) {
						e.printStackTrace();
						Log.d("TAG", "打印字符串异常：" + e);
//						msg.obj = "打印异常：" + e.getMessage();
//						msg.what = 2;
//						CrashReport.postCatchedException(e);
//						handler.sendMessage(msg);
					}
				}
			}
		}).start();

	}


	/**
	 * 网络图片转换为Bitmap
	 *
	 * @Author: ChengBin
	 * @Time: 16/4/5 下午2:41
	 */
	public static Bitmap netPicToBmp(String src) {
		try {
			Log.d("FileUtil", src);
			URL url = new URL(src);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.connect();
			InputStream input = connection.getInputStream();
			Bitmap myBitmap = BitmapFactory.decodeStream(input);

			//设置固定大小
			//需要的大小
			float newWidth = 200f;
			float newHeigth = 200f;

			//图片大小
			int width = myBitmap.getWidth();
			int height = myBitmap.getHeight();

			//缩放比例
			float scaleWidth = newWidth / width;
			float scaleHeigth = newHeigth / height;
			Matrix matrix = new Matrix();
			matrix.postScale(scaleWidth, scaleHeigth);

			Bitmap bitmap = Bitmap.createBitmap(myBitmap, 0, 0, width, height, matrix, true);
			return bitmap;
		} catch (IOException e) {
			// Log exception
			return null;
		}
	}


	public Bitmap convertToBitmap(String path, int w, int h) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		// 设置为ture只获取图片大小
		opts.inJustDecodeBounds = true;
		opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
		// 返回为空
		BitmapFactory.decodeFile(path, opts);
		int width = opts.outWidth;
		int height = opts.outHeight;
		float scaleWidth = 0.f, scaleHeight = 0.f;
		if (width > w || height > h) {
			// 缩放
			scaleWidth = ((float) width) / w;
			scaleHeight = ((float) height) / h;
		}
		opts.inJustDecodeBounds = false;
		float scale = Math.max(scaleWidth, scaleHeight);
		opts.inSampleSize = (int)scale;
		WeakReference<Bitmap> weak = new WeakReference<Bitmap>(BitmapFactory.decodeFile(path, opts));
		return Bitmap.createScaledBitmap(weak.get(), w, h, true);
	}
	@Override
	public void disconnect() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					if (deviceManager != null) {
						deviceManager.disconnect();				
						deviceManager = null;
//						baseActivity.showMessage("设备断开成功...", Const.MessageTag.TIP);
					}
				} catch (Exception e) {
//					baseActivity.showMessage("设备断开异常:" + e, Const.MessageTag.TIP);
				}
			}
		}).start();
	}

	@Override
	public boolean isDeviceAlive() {
		boolean ifConnected = ( deviceManager== null ? false : deviceManager.getDevice().isAlive());
        return ifConnected;
	}

	@Override
	public K21CardReader getCardReaderModuleType() {
		K21CardReader cardReader=(K21CardReader) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_CARDREADER);
		return cardReader;
	}

	@Override
	public EmvModule getEmvModuleType() {
		EmvModule emvModule=(EmvModule) deviceManager.getDevice().getExModule("EMV_INNERLEVEL2");
		return emvModule;
	}

	@Override
	public ICCardModule getICCardModule() {
		ICCardModule iCCardModule=(ICCardModule) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_ICCARDREADER);
		return iCCardModule;
	}

	@Override
	public IndicatorLight getIndicatorLight() {
		IndicatorLight indicatorLight=(IndicatorLight) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_INDICATOR_LIGHT);
		return indicatorLight;
	}

	@Override
	public K21Pininput getK21Pininput() {
		K21Pininput k21Pininput=(K21Pininput) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_PININPUT);
		return k21Pininput;
	}

	@Override
	public Printer getPrinter() {
		Printer printer=(Printer) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_PRINTER);
		printer.init();
		return printer;
	}

	@Override
	public K21RFCardModule getRFCardModule() {
		K21RFCardModule rFCardModule=(K21RFCardModule) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_RFCARDREADER);
		return rFCardModule;
	}

	@Override
	public BarcodeScanner getBarcodeScanner() {
		BarcodeScannerManager barcodeScannerManager=(BarcodeScannerManager) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_BARCODESCANNER);
		BarcodeScanner scanner = barcodeScannerManager.getDefault();
		return scanner;
	}

	@Override
	public SecurityModule getSecurityModule() {
		SecurityModule securityModule=(SecurityModule) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_SECURITY);
		return securityModule;
	}

	@Override
	public Storage getStorage() {
		Storage storage=(Storage) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_STORAGE);
		return storage;
	}

	@Override
	public K21Swiper getK21Swiper() {
		K21Swiper k21Swiper=(K21Swiper) deviceManager.getDevice().getStandardModule(ModuleType.COMMON_SWIPER);
		return k21Swiper;
	}

	@Override
	public Device getDevice() {
		return deviceManager.getDevice();
	}
	
	@Override
	public SerialModule getUsbSerial() {
		SerialModule k21Serial=(SerialModule) deviceManager.getDevice().getExModule(ExModuleType.USBSERIAL);
		return k21Serial;
	}

	@Override
	public SmModule getSmModule() {
		SmModule smModule = (SmModule)deviceManager.getDevice().getStandardModule(ModuleType.COMMON_SM);
		return smModule;
	}
	
}
